/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CalendarPanel.java
 *
 * Created on May 25, 2009, 4:25:08 AM
 */

package matpred;

import bdl.UtilityBean;
import entities.GCalendar;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SpinnerListModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import utilities.Generator;
import utilities.Utility;
import utilities.entities.SCalendar;

/**
 *
 * @author Demola
 */
public class CalendarPanel extends javax.swing.JPanel {

    /** Creates new form CalendarPanel */
    public CalendarPanel() {
        initComponents();
        calendarList = new ArrayList();
        dlm = new DefaultListModel();
        jList1.setModel(dlm);
        loadCalendars();
    }

    public static CalendarPanel getCalendarPanel(){
        if(calendarPanel == null){
            calendarPanel = new CalendarPanel();
        }
        return calendarPanel;
    }

    public boolean isSaved(){
        return saved;
    }

    private void setTable(){

        jTable1.getColumnModel().getColumn(0).setMinWidth(40);
        jTable1.getColumnModel().getColumn(1).setMinWidth(130);
        jTable1.getColumnModel().getColumn(2).setMinWidth(40);
        jTable1.getColumnModel().getColumn(3).setMinWidth(40);

        for(int i = 5; i < dtm.getColumnCount(); i++){
            jTable1.getColumnModel().getColumn(i).setCellRenderer(new NewCellRenderer());
            jTable1.getColumnModel().getColumn(i).setMinWidth(60);
        }

        for(int i = 0; i < dtm.getColumnCount(); i++){
            jTable1.getColumnModel().getColumn(i).setResizable(false);
        }
    }

    private void loadCalendars(){
        GCalendar tcal = UtilityBean.getCalendar();
        if(tcal == null || tcal.getNYears() == -1){
            return;
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(tcal.getStartDate());
        startDate = cal.getTime();
        count = 1;

        nyears = tcal.getNYears();
        ncols = tcal.getNColumns();
        ndiv = tcal.getNDivisible();

        generate(cal, tcal.getOffset());
        for(int i = 0; i < tcal.getNTimes(); i++){
            next(tcal.getOffset());
//            System.out.println("count i: " + i);
        }
    }

    private void generate(Calendar cal, int ofset){
        String [] days = {"", "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"};
        int nd = cal.get(Calendar.DAY_OF_WEEK);
        calName = " " + days[nd] + " Calendar";

        dtm = Generator.generate(cal.getTime(), nyears, ncols, -1);
        if(ofset > 0)
            dtm = Utility.incrMonitors(dtm, ofset);
        gcal = new GCalendar(1, "Default", cal.getTime(), nyears, ncols, ndiv, 0, 0);
        dlm.clear();
        calendarList.clear();
        calendarList.add(new SCalendar(dtm, calName));
        dlm.addElement(calName);
        jTable1.setModel(dtm);
        setTable();
    }

    private void next(int ofset){
        int div = count * ndiv;
        dtm = Generator.generate(startDate, nyears, ncols, div);
        if(ofset > 0)
            dtm = Utility.incrMonitors(dtm, ofset);
        gcal.setNTimes(count);
        String cname = calName + " " + div;
        calendarList.add(new SCalendar(dtm, cname, div));
        jTable1.setModel(dtm);
        dlm.addElement(cname);
        setTable();
        jList1.setSelectedIndex(count);
        ++count;
    }

    public ArrayList<SCalendar> getCalendars(){
        return calendarList;
    }

    public SCalendar getDefaultCalendar(){
        if(!calendarList.isEmpty())
            return calendarList.get(0);
        else
            return null;
    }

    public void saveCalendar(){
        UtilityBean.updateCalendar(gcal);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel5 = new javax.swing.JLabel();
        jSpinner3 = new javax.swing.JSpinner();
        jLabel6 = new javax.swing.JLabel();
        jSpinner4 = new javax.swing.JSpinner();
        jTextField1 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel5.setText("day");

        jSpinner3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jSpinner3.setModel(new javax.swing.SpinnerNumberModel(1, 1, 31, 1));
        jSpinner3.setEditor(new javax.swing.JSpinner.NumberEditor(jSpinner3, ""));

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel6.setText("month");

        jSpinner4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jSpinner4.setModel(new javax.swing.SpinnerListModel(new String[] {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}));

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel7.setText("year");

        jLabel1.setText("Number of Years");

        jLabel2.setText("columns");

        jLabel3.setText("divisible number");

        jTable1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Generate");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        jButton2.setText("Next");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jList1);

        jButton3.setText("Clear");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jButton4.setText("Reset Monitors");
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(6, 6, 6)
                                .addComponent(jSpinner3, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSpinner4, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField4)
                                    .addComponent(jTextField3)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE))))
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(162, 162, 162)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6)
                                .addComponent(jLabel7)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jSpinner3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jSpinner4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton4)
                                .addComponent(jButton2)))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped
        char c = evt.getKeyChar();
        if(c < '0' || c > '9')
            evt.consume();
        if(jTextField1.getText().length() >= 4)
            evt.consume();
    }//GEN-LAST:event_jTextField1KeyTyped

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        //GENERATE
        Calendar cal = Calendar.getInstance();
        date = (Integer) jSpinner3.getValue();
        SpinnerListModel lm = (SpinnerListModel) jSpinner4.getModel();
        month = lm.getList().indexOf(jSpinner4.getValue());
        year = 0;
        try{
            year = Integer.parseInt(jTextField1.getText());
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Please enter a valid year");
            return;
        }
        if(year < 1800){
            JOptionPane.showMessageDialog(null, "Please enter a valid year");
            return;
        }
        cal.set(year, month, date);
        startDate = cal.getTime();
        count = 1;

        try{
            nyr = Integer.parseInt(jTextField2.getText());
            ncols = Integer.parseInt(jTextField3.getText());
            ndiv = Integer.parseInt(jTextField4.getText());
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, "One of the values entered is not in the correct format. " +
                    "Please check the inputs");
            return;
        }

        nyr = Integer.parseInt(jTextField2.getText());
        nyears = nyr + year - 1;
        ncols = Integer.parseInt(jTextField3.getText());

        saved = false;
        generate(cal, 0);

    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        next(0);
        saved = false;
    }//GEN-LAST:event_jButton2MouseClicked

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
         int indx = jList1.getSelectedIndex();
         if(indx == -1) return;
         dtm = calendarList.get(indx).getTable();
         if(dtm == null) return;
         setTable();
         jTable1.setModel(dtm);
    }//GEN-LAST:event_jList1ValueChanged

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
        if(dlm.isEmpty()){
            JOptionPane.showMessageDialog(calendarPanel, "No generated calendars");
            return;
        }
        String message = "This will delete all the calendars that have been generated";
        int opt = JOptionPane.showConfirmDialog(null, message, "Are you sure?",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(opt == JOptionPane.YES_OPTION){
            dlm.clear();
            calendarList.clear();
            dtm.setRowCount(0);
            dtm.setColumnCount(0);

        }
    }//GEN-LAST:event_jButton3MouseClicked

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
         loadCalendars();
    }//GEN-LAST:event_formComponentShown

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
         GCalendar tcal = UtilityBean.getCalendar();
         tcal.setOffset(0);
         UtilityBean.updateCalendar(tcal);
         loadCalendars();
         JOptionPane.showMessageDialog(null, "Monitors number has been reset");
    }//GEN-LAST:event_jButton4MouseClicked



    private boolean saved = true;
    private GCalendar gcal;
    private ArrayList<SCalendar> calendarList;
    private String calName;
    private DefaultListModel dlm;
    private Date startDate;
    private int nyr, ncols, ndiv, nyears, count;
    private int year, month, date;
    private DefaultTableModel dtm;
    private static CalendarPanel calendarPanel;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSpinner jSpinner3;
    private javax.swing.JSpinner jSpinner4;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables


    class NewCellRenderer implements TableCellRenderer{

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, final boolean isSelected, boolean hasFocus, int row, int column) {
            JTable cellTable = new JTable(new DefaultTableModel(new Object[][]{}, new String[] {"", ""})){

                @Override
                public boolean isRowSelected(int row) {
                    return isSelected;
                }
            };
            cellTable.setTableHeader(null);
            DefaultTableModel dtm = (DefaultTableModel)cellTable.getModel();
            Object [] val = (Object[])value;
            dtm.addRow(val);
            return cellTable;
        }
    }
}
